﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace XKControlLib.Common
{
    public class DataEntry<T> where T : new()
    {
        private DataTable dt;


        public DataEntry(DataTable datatable)
        {
            this.dt = datatable;
        }

     

        /// <summary>
        /// 创建 System.Collections.Generic.List
        /// </summary>
        /// <returns></returns>
        public List<T> ToList()
        {
            List<T> ts = new List<T>();// 定义集合 
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                foreach (PropertyInfo pi in propertys)
                {
                    //Type type = typeof(T);// 获得此模型的类型 
                    string tempName = pi.Name;
                    if (dt.Columns.Contains(tempName))
                    {
                        if (!pi.CanWrite)// 判断此属性是否有Setter   
                        {
                            continue;
                        }
                        object value = dr[tempName];
                        if (value != DBNull.Value)
                        {
                            pi.SetValue(t, value, null);
                        }
                    }
                }
                ts.Add(t);
            }
            return ts;
        }

        public static List<T> ToList(DataTable data)
        {
            List<T> ts = new List<T>();// 定义集合 
            string tempName = "";
            foreach (DataRow dr in data.Rows)
            {
                T t = new T();
                PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;  // 检查DataTable是否包含此列    
                    if (data.Columns.Contains(tempName))
                    {
                        if (!pi.CanWrite)// 判断此属性是否有Setter   
                        {
                            continue;
                        }
                        object value = dr[tempName];
                        if (value != DBNull.Value)
                        {
                            pi.SetValue(t, value, null);
                        }
                    }
                }
                ts.Add(t);
            }
            return ts;
        }


    }
}
